import { message } from 'ant-design-vue';
import io from 'socket.io-client';
import { onMounted, onUnmounted } from 'vue';
import { SocketURL } from '../config/config';

export const useWebSocket = () => {
  const socket = io(SocketURL);

  const init = () => {
    bindEvent();
  };

  function bindEvent() {
    socket.on('connect', function () {
      console.log('连上了');
    });

    socket.on('disconnect', function () {
      console.log('连接断开了');
    });

    socket.on('error', (error) => {
      console.log('出现不知名的错误,可能是网络异常,错误原因为', error);
      message.error('网络异常');
    });

    socket.on('reconnect', (attempt) => {
      message.success('重新连接成功');
    });
  }
  onMounted(() => {
    init();
  });

  onUnmounted(() => {
    socket.close();
  });

  return socket;
};
